import CryptoJS from "crypto-js";

const CRYPTO_KEY = "pptist";

/**
 * 加密
 *
 * @param msg
 * @param key
 * @param Appid
 * @returns
 */
export const encryptPpt = (msg: any, key: any, Appid: any) => {
  try {
    const keyStr = encParse(`sqx${key}${Appid}`);
    const encryptedStr = CryptoJS.DES.encrypt(msg, keyStr, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encryptedStr.toString();
  } catch (e) {}
};

export const decryptPpt = (msg: string, key: string, Appid: string) => {
  try {
	const keyStr = encParse(`sqx${key}${Appid}`);
    const decryptedStr = CryptoJS.DES.decrypt(msg, keyStr, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return decryptedStr.toString(CryptoJS.enc.Utf8);
  } catch (e) {}
};

/**
 * 处理密钥字符格式
 * @param: key 需要转格式的字符
 */
function encParse(key:string) {
	return CryptoJS.enc.Utf8.parse(key)
}

/**
 * 加密
 * @param msg 待加密字符串
 */
export const encrypt = (msg: string) => {
  return CryptoJS.AES.encrypt(msg, CRYPTO_KEY).toString();
};

/**
 * 解密
 * @param ciphertext 待解密字符串
 */
export const decrypt = (ciphertext: string) => {
  const bytes = CryptoJS.AES.decrypt(ciphertext, CRYPTO_KEY);
  return bytes.toString(CryptoJS.enc.Utf8);
};
